package com.java.common.utils;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.java.common.constant.HttpStatus;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.java.common.utils.text.Convert;

/**
 * 客户端工具类
 * 
 * @author Administrator
 */
public class ServletUtils {

    private static final String XML_HTTP_REQUEST = "XMLHttpRequest";

    private static final String DOT = ".";

    private static final String XML = "xml";

    private static final String JSON = "json";

    private static final String DOT_XML = DOT + XML;

    private static final String DOT_JSON = DOT + JSON;

    private static final String APPLICATION_JSON = "application/json";

    private static final String UTF_8 = "utf-8";

    private static final String USER_AGENT_NAME = "User-Agent";

    /**
     * 获取String参数
     */
    public static String getParameter(String name) {
        return getRequest().getParameter(name);
    }

    /**
     * 获取String参数
     */
    public static String getParameter(String name, String defaultValue) {
        return Convert.toStr(getRequest().getParameter(name), defaultValue);
    }

    /**
     * 获取Integer参数
     */
    public static Integer getParameterToInt(String name) {
        return Convert.toInt(getRequest().getParameter(name));
    }

    /**
     * 获取Integer参数
     */
    public static Integer getParameterToInt(String name, Integer defaultValue) {
        return Convert.toInt(getRequest().getParameter(name), defaultValue);
    }

    /**
     * 获取request
     */
    public static HttpServletRequest getRequest() {
        return getRequestAttributes().getRequest();
    }

    /**
     * 获取response
     */
    public static HttpServletResponse getResponse() {
        return getRequestAttributes().getResponse();
    }

    /**
     * 获取session
     */
    public static HttpSession getSession() {
        return getRequest().getSession();
    }

    public static ServletRequestAttributes getRequestAttributes() {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        return (ServletRequestAttributes) attributes;
    }

    /**
     * 将字符串渲染到客户端
     * 
     * @param response 渲染对象
     * @param string   待渲染的字符串
     * @param code     状态码
     * @return String
     */
    public static String renderString(HttpServletResponse response, String string, int code) {
        try {
            response.setStatus(code);
            response.setContentType(APPLICATION_JSON);
            response.setCharacterEncoding(UTF_8);
            response.getWriter().print(string);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将字符串渲染到客户端
     *
     * @param response 渲染对象
     * @param string   待渲染的字符串
     * @return String
     */
    public static String renderString(HttpServletResponse response, String string) {
        return renderString(response, string, HttpStatus.SUCCESS);
    }

    /**
     * 是否是Ajax异步请求
     * 
     * @param request
     */
    public static boolean isAjaxRequest(HttpServletRequest request) {
        String accept = request.getHeader("accept");
        if (accept != null && accept.indexOf(APPLICATION_JSON) != -1) {
            return true;
        }

        String xRequestedWith = request.getHeader("X-Requested-With");
        if (xRequestedWith != null && xRequestedWith.indexOf(XML_HTTP_REQUEST) != -1) {
            return true;
        }

        String uri = request.getRequestURI();
        if (StringUtils.inStringIgnoreCase(uri, DOT_JSON, DOT_XML)) {
            return true;
        }

        String ajax = request.getParameter("__ajax");
        if (StringUtils.inStringIgnoreCase(ajax, JSON, XML)) {
            return true;
        }
        return false;
    }
    
    public static boolean isAjaxRequest() {
        return isAjaxRequest(getRequest());
    }

    /**
     * 获取请求头
     * 
     * @author yilabao
     * @date 2021年1月30日
     * @param name
     * @return String
     */
    public static String getHeader(String name) {
        return getRequest().getHeader(name);
    }

    /**
     * 获取用户代理
     * 
     * @author yilabao
     * @date 2021年1月30日
     * @return String
     */
    public static String getUserAgent() {
        return getHeader(USER_AGENT_NAME);
    }

    /**
     * 获取完整的请求路径，包括：域名，端口，上下文访问路径
     */
    public static String getDomain(HttpServletRequest request) {
        StringBuffer url = request.getRequestURL();
        String contextPath = request.getServletContext().getContextPath();
        return url.delete(url.length() - request.getRequestURI().length(), url.length()).append(contextPath).toString();
    }

    /**
     * 获取完整的请求路径，包括：域名，端口，上下文访问路径
     * 
     * @author yilabao
     * @date 2021年2月26日
     * @return String
     */
    public static String getBasePath() {
        return getDomain(getRequest());
    }

    public static String getServerPath() {
        return getBasePath();
    }

    /**
     * 获取平台类型
     * 
     * @author yilabao
     * @date 2021年4月26日
     * @return Integer
     */
    public static Integer getPlatform() {
        String platformName = "platform";
        String platform = getHeader(platformName);
        return NumberUtils.toInt(platform, 0);
    }

    /**
     * 是否微信小程序请求
     *
     * @author yilabao
     * @date 2021年9月23日
     * @return boolean
     */
    public static boolean isWeapp() {
        String weapp = "weapp";
        String mpWeixin = "mp-weixin";
        String evnName = "env";
        String env = getHeader(evnName);
        return weapp.equals(env) || mpWeixin.equals(env);
    }

    /**
     * 是否是json请求
     * 
     * @author yilabao
     * @date 2021年9月7日
     * @param contentType
     * @return boolean
     */
    public static boolean isJsonRequest(String contentType) {
        return StringUtils.startsWithIgnoreCase(contentType, APPLICATION_JSON);
    }

    /**
     * 是否是json请求
     * 
     * @author yilabao
     * @date 2021年9月7日
     * @param request
     * @return boolean
     */
    public static boolean isJsonRequest(HttpServletRequest request) {
        return isJsonRequest(request.getContentType());
    }

}